package com.anjie.powerproject.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anjie.powerproject.common.Result;
import com.anjie.powerproject.entity.Point;
import com.anjie.powerproject.entity.StationInfo;
import com.anjie.powerproject.pojo.dto.StationInfoDTO;
import com.anjie.powerproject.service.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;


@Controller
@RequestMapping("StationInfo")
public class StationInfoController {

    @Autowired
    private StationInfoService stationInfoService;
    @Autowired
    private PointService pointService;

    /**
     * 添加基本信息
     * @param jsonArray
     * @return
     */
    @PostMapping("/addInfo")
    @ResponseBody
    public Map addInfo(@RequestBody JSONArray jsonArray) {
        Map res = new HashMap();
        List<String> duplicateList = new ArrayList<>();
        List<StationInfo> addList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (stationInfoService.checkInfoName(jsonObject.getString("stationName"))) {
                String stationName = jsonObject.getString("stationName");
                duplicateList.add(stationName + "此名称已存在");
            } else {
                StationInfo stationInfo = new StationInfo();
                stationInfo.setStationName(jsonObject.getString("stationName"));
                stationInfo.setStationArea(jsonObject.getString("stationArea"));
                stationInfo.setBuildingArea(jsonObject.getString("buildingArea"));
                stationInfo.setConstructionYear(jsonObject.getString("constructionYear"));
                stationInfo.setStationAdress(jsonObject.getString("stationAdress"));
                stationInfo.setCityCode(jsonObject.getString("cityCode"));
                stationInfo.setBatteryCode(jsonObject.getString("batteryCode"));
                stationInfo.setBatteryPointId(Integer.valueOf(jsonObject.getString("batteryPointId")));
                stationInfo.setEnergyCode(jsonObject.getString("energyCode"));
                stationInfo.setEnergyPointId(Integer.valueOf(jsonObject.getString("energyPointId")));
//                stationInfo.setTemperatureCode(jsonObject.getString("temperatureCode"));
//                stationInfo.setTemperaturePointId(Integer.valueOf(jsonObject.getString("temperaturePointId")));
                addList.add(stationInfo);
            }
        }
        if ( duplicateList.size() == 0) {
            stationInfoService.saveStationInfo(addList);
            res.put("status", "添加成功");
        } else {
            res.put("statu", duplicateList);
        }
        return  res;
    }

    /**
     * 删除单条信息，根据id
     * @param id
     * @return
     */
        @PostMapping("/deleteInfo")
    @ResponseBody
    public String deleteInfo(Integer id){
        stationInfoService.deleteStationInfoById(id);
        return "success";
    }

    /**
     * 显示所有信息
      * @return
     */
    @PostMapping("/viewInfo")
    @ResponseBody
    public JSONArray viewInfo(){
        List<StationInfo> list = stationInfoService.findAllInfo();
        String string = JSON.toJSON(list).toString();
        System.out.println(string);
        com.alibaba.fastjson.JSONArray jsonArray = JSONObject.parseArray(string);
        return jsonArray;
    }

    /**
     * 处理修改请求
     * @param jsonObject
     * @return
     */
    @PostMapping("/editInfo")
    @ResponseBody
    public String editInfo(HttpServletRequest request, @RequestBody JSONObject jsonObject){
        StationInfo stationInfo = new StationInfo();
        Integer id = jsonObject.getInteger("id");
        StationInfo a = new StationInfo();
        List<StationInfo> stationInfoList = new ArrayList<>();
        if(id==null){
            stationInfo.setStationName(jsonObject.getString("stationName"));
            stationInfo.setStationArea(jsonObject.getString("stationArea"));
            stationInfo.setBuildingArea(jsonObject.getString("buildingArea"));
            stationInfo.setConstructionYear(jsonObject.getString("constructionYear"));
            stationInfo.setStationAdress(jsonObject.getString("stationAdress"));
            stationInfo.setCityCode(jsonObject.getString("cityCode"));
            stationInfo.setBatteryCode(jsonObject.getString("batteryCode"));
            stationInfo.setBatteryPointId(Integer.valueOf(jsonObject.getString("batteryPointId")));
            stationInfo.setEnergyCode(jsonObject.getString("energyCode"));
            stationInfo.setEnergyPointId(Integer.valueOf(jsonObject.getString("energyPointId")));
//            stationInfo.setTemperatureCode(jsonObject.getString("temperatureCode"));
//            stationInfo.setTemperaturePointId(Integer.valueOf(jsonObject.getString("temperaturePointId")));
            stationInfoList.add(stationInfo);
            stationInfoService.saveStationInfo(stationInfoList);
        }else {
            stationInfo.setId(jsonObject.getInteger("id"));
            stationInfo.setStationName(jsonObject.getString("stationName"));
            stationInfo.setStationArea(jsonObject.getString("stationArea"));
            stationInfo.setBuildingArea(jsonObject.getString("buildingArea"));
            stationInfo.setConstructionYear(jsonObject.getString("constructionYear"));
            stationInfo.setStationAdress(jsonObject.getString("stationAdress"));
            stationInfo.setCityCode(jsonObject.getString("cityCode"));
            stationInfo.setBatteryCode(jsonObject.getString("batteryCode"));
            stationInfo.setBatteryPointId(Integer.valueOf(jsonObject.getString("batteryPointId")));
            stationInfo.setEnergyCode(jsonObject.getString("energyCode"));
            stationInfo.setEnergyPointId(Integer.valueOf(jsonObject.getString("energyPointId")));
//            stationInfo.setTemperatureCode(jsonObject.getString("temperatureCode"));
//            stationInfo.setTemperaturePointId(Integer.valueOf(jsonObject.getString("temperaturePointId")));
            stationInfoService.updateStationInfo(stationInfo);
        }

        String logo = jsonObject.getString("logo");
        if (logo != null && logo != "" && logo.split(",").length > 1) {
            String base = request.getServletContext().getRealPath("WEB-INF/classes/static/images/");
            // 覆盖logo图
            byte[] decode = Base64.getDecoder().decode(logo.split(",")[1]);
            File file = new File(base + "logo.png");
            try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
                bos.write(decode);
                bos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "success";
    }

    /**
     * 跳转到编辑页面
     * @param id
     * @return
     */
    @PostMapping("/infoEdit")
    @ResponseBody
    public StationInfoDTO infoEdit(Integer id){
        StationInfo stationInfo = new StationInfo();
        stationInfo = stationInfoService.findStationInfoById(id);
        StationInfoDTO stationInfoDTO=new StationInfoDTO();
        //把stationInfo的字段复制到stationInfoDTO（仅复制相同字段名）
        BeanUtils.copyProperties(stationInfo,stationInfoDTO);

        if(stationInfo.getBatteryPointId()!=null) {
            Point batteryPoint = pointService.getPointById(stationInfo.getBatteryPointId());
            stationInfoDTO.setBatteryName(batteryPoint.getPointName());
            stationInfoDTO.setBatteryPointId(batteryPoint.getId());
        }else {
            stationInfoDTO.setBatteryName("无对应点位");
            stationInfoDTO.setBatteryPointId(0);
        }
        if(stationInfo.getEnergyPointId()!=null) {
            Point energyPoint = pointService.getPointById(stationInfo.getEnergyPointId());
            stationInfoDTO.setEnergyName(energyPoint.getPointName());
            stationInfoDTO.setEnergyPointId(energyPoint.getId());
        } else{
            stationInfoDTO.setEnergyName("无对应点位");
            stationInfoDTO.setEnergyPointId(0);
        }
//        Point temperaturePoint=pointService.getPointById(stationInfo.getTemperaturePointId());
//        stationInfoDTO.setTemperatureName(temperaturePoint.getPointName());
//        stationInfoDTO.setTemperaturePointId(temperaturePoint.getId());
//        System.out.println(stationInfoDTO.toString());
        return stationInfoDTO;
    }

    @PostMapping(value = "/logo/upload")
    @ResponseBody
    public Result<Void> logoUpload(HttpServletRequest request, @RequestParam("logo") MultipartFile[] logo) {
        try {
            String base = request.getServletContext().getRealPath("WEB-INF/classes/static/images/");
            String fileName = "logo.png";

            if (logo != null) {
                File logoFile = new File(base + fileName);
                FileUtils.copyInputStreamToFile(logo[0].getInputStream(), logoFile);
            }
        } catch (Exception e) {
            return Result.error(String.format("logo上传失败 %s", e.getMessage()));
        }

        return Result.ok(null);
    }
}